<?php
/**
 * 系统助手类
 *
 * @author        chenfenghua <843958575@qq.com>
 * @copyright     Copyright (c) 2015-2016 Yiishop. All rights reserved.
 * @link          http://www.yiishop.com.cn
 * @package       BageCMS.Tools
 * @license       http://www.yiishop.com.cn/license
 * @version       v2.0.0
 */

namespace app\models;


class Utils {
    /**
     * 发送POST请求
     *
     * @param string $url
     * @param array $post
     * @throws Exception
     * @return string
     */
    public static function post($url, $post = null)
    {
        //对空格进行转义
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        //https 请求
        if(strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https" )
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        if (is_array($post) && 0 < count($post))
        {
            $post_body_string = "";
            $post_multipart = false;
            foreach ($post as $k => $v)
            {
                if("@" != substr($v, 0, 1))//判断是不是文件上传
                {
                    $post_body_string .= "$k=" . urlencode($v) . "&";
                }
                else//文件上传用multipart/form-data，否则用www-form-urlencoded
                {
                    $post_multipart = true;
                }
            }
            curl_setopt($ch, CURLOPT_POST, true);
            if ($post_multipart)
            {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
            }
            else
            {
                curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_body_string,0,-1));
            }
        }
        $reponse = curl_exec($ch);

//        if (curl_errno($ch))
//        {
//            throw new Exception(curl_error($ch), 0);
//        }
//        else
//        {
//            $http_status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//            if (200 !== $http_status_code)
//            {
//                throw new Exception($reponse,$http_status_code);
//            }
//        }
        curl_close($ch);
        return $reponse;
    }

    /**
     * 验证邮箱
     * @param $str
     * @return bool
     */
    public static function email( $str ) {
        if ( empty( $str ) )
            return true;
        $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
        if ( strpos( $str, '@' ) !== false && strpos( $str, '.' ) !== false ) {
            if ( preg_match( $chars, $str ) ) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 验证手机号码
     * @param $str
     * @return bool
     */
    public static function mobile( $str ) {
        if ( empty( $str ) ) {
            return false;
        }

        return preg_match( '#^13[\d]{9}$|^14[0-9]\d{8}|^15[0-9]\d{8}$|^17[0-9]\d{8}$|^18[0-9]\d{8}$#', $str );
    }

    /**
     * 验证固定电话
     * @param $str
     * @return bool
     */
    public static function tel( $str ) {
        if ( empty( $str ) ) {
            return false;
        }
        return preg_match( '/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/', trim( $str ) );

    }

    /**
     * 验证qq号码
     * @param $str
     * @return bool
     */
    public static function qq( $str ) {
        if ( empty( $str ) ) {
            return false;
        }

        return preg_match( '/^[1-9]\d{4,12}$/', trim( $str ) );
    }

    /**
     * 验证邮政编码
     * @param $str
     * @return bool
     */
    public static function zipCode( $str ) {
        if ( empty( $str ) ) {
            return false;
        }

        return preg_match( '/^[1-9]\d{5}$/', trim( $str ) );
    }

    /**
     * 验证ip
     * @param $str
     * @return bool
     */
    public static function ip( $str ) {
        if ( empty( $str ) )
            return false;

        if ( ! preg_match( '#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $str ) ) {
            return false;
        }

        $ip_array = explode( '.', $str );

        //真实的ip地址每个数字不能大于255（0-255）
        return ( $ip_array[0] <= 255 && $ip_array[1] <= 255 && $ip_array[2] <= 255 && $ip_array[3] <= 255 ) ? true : false;
    }

    /**
     * 验证身份证(中国)
     * @param $str
     * @return bool
     */
    public static function idCard( $str ) {
        $str = trim( $str );
        if ( empty( $str ) )
            return false;

        if ( preg_match( "/^([0-9]{15}|[0-9]{17}[0-9a-z])$/i", $str ) )
            return true;
        else
            return false;
    }

    /**
     * 验证网址
     * @param $str
     * @return bool
     */
    public static function url( $str ) {
        if ( empty( $str ) )
            return false;

        return preg_match( '#(http|https|ftp|ftps)://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?#i', $str ) ? true : false;
    }

    /**
     * 字符截取
     *
     * @param $string
     * @param $length
     * @param $dot
     * @param $charset
     * @return string
     */
    public static function cutstr( $string, $length, $dot = '...', $charset = 'utf-8' ) {
        if ( strlen( $string ) <= $length )
            return $string;

        $pre = chr( 1 );
        $end = chr( 1 );
        $string = str_replace( array ( '&amp;' , '&quot;' , '&lt;' , '&gt;' ), array ( $pre . '&' . $end , $pre . '"' . $end , $pre . '<' . $end , $pre . '>' . $end ), $string );

        $strcut = '';
        if ( strtolower( $charset ) == 'utf-8' ) {

            $n = $tn = $noc = 0;
            while ( $n < strlen( $string ) ) {

                $t = ord( $string[$n] );
                if ( $t == 9 || $t == 10 || ( 32 <= $t && $t <= 126 ) ) {
                    $tn = 1;
                    $n ++;
                    $noc ++;
                } elseif ( 194 <= $t && $t <= 223 ) {
                    $tn = 2;
                    $n += 2;
                    $noc += 2;
                } elseif ( 224 <= $t && $t <= 239 ) {
                    $tn = 3;
                    $n += 3;
                    $noc += 2;
                } elseif ( 240 <= $t && $t <= 247 ) {
                    $tn = 4;
                    $n += 4;
                    $noc += 2;
                } elseif ( 248 <= $t && $t <= 251 ) {
                    $tn = 5;
                    $n += 5;
                    $noc += 2;
                } elseif ( $t == 252 || $t == 253 ) {
                    $tn = 6;
                    $n += 6;
                    $noc += 2;
                } else {
                    $n ++;
                }

                if ( $noc >= $length ) {
                    break;
                }

            }
            if ( $noc > $length ) {
                $n -= $tn;
            }

            $strcut = substr( $string, 0, $n );

        } else {
            for ( $i = 0; $i < $length; $i ++ ) {
                $strcut .= ord( $string[$i] ) > 127 ? $string[$i] . $string[++ $i] : $string[$i];
            }
        }

        $strcut = str_replace( array ( $pre . '&' . $end , $pre . '"' . $end , $pre . '<' . $end , $pre . '>' . $end ), array ( '&amp;' , '&quot;' , '&lt;' , '&gt;' ), $strcut );

        $pos = strrpos( $strcut, chr( 1 ) );
        if ( $pos !== false ) {
            $strcut = substr( $strcut, 0, $pos );
        }
        return $strcut . $dot;
    }

    /**
     * 随机生成6位数
     *
     * @param int $length
     * @return null|string
     */
    public static function getRandChar($length = 6){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }

    /**
     * 订单号生成
     */
    public static function build_order_no()
    {
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    /**
     * 生成付款/发货等订单流水号
     *
     * 10：付款单号 11：退款单号 12:退款申请单号  20：发货单号 21：退货单号 22：退货申请单号
     *
     * @param $prefix
     * @return string
     */
    public static function bills_no($prefix = '10')
    {
        return $prefix.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    /**
     * 32位转10位
     *
     * @param $str
     * @return bool|string
     */
    public static function base10To32($str)
    {
        if (strlen($str) == 0) return false;

        $str =  base_convert ($str,10,32);
        return $str;
    }

    /**
     * 10位转32位
     *
     * @param $str
     * @return bool|string
     */
    public static function base32To10($str)
    {
        if (strlen($str) == 0) return false;
        $enstr =  base_convert ($str,32,10);

        return $enstr;
    }
}